import 'dart:collection';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nft/provider/LoginProvider.dart';
import 'package:provider/provider.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../../api/API.dart';

class ProductNew {
  late int id;
  late String productCode;
  late String productTitle;
  late String productImage;
  late String productDesc;
  late int initPrice;
  late int newPrice;
  late int productCount;
  late int productStock;
  late int orgAuthId;
  late String createTime;
  late String updateTime;
  late String productTime;
  late int dFlag;
  late String productDescImage;

  static ProductNew? fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    ProductNew productNewBean = ProductNew();
    productNewBean.id = map['id'];
    productNewBean.productCode = map['productCode'];
    productNewBean.productTitle = map['productTitle'];
    productNewBean.productImage = map['productImage'];
    productNewBean.productDesc = map['productDesc'];
    productNewBean.initPrice = map['initPrice'];
    productNewBean.newPrice = map['newPrice'];
    productNewBean.productCount = map['productCount'];
    productNewBean.productStock = map['productStock'];
    productNewBean.orgAuthId = map['orgAuthId'];
    productNewBean.createTime = map['createTime'];
    productNewBean.updateTime = map['updateTime'];
    productNewBean.productTime = map['productTime'];
    productNewBean.dFlag = map['dFlag'];
    productNewBean.productDescImage = map['productDescImage'];
    return productNewBean;
  }

  Map toJson() => {
        "id": id,
        "productCode": productCode,
        "productTitle": productTitle,
        "productImage": productImage,
        "productDesc": productDesc,
        "initPrice": initPrice,
        "newPrice": newPrice,
        "productCount": productCount,
        "productStock": productStock,
        "orgAuthId": orgAuthId,
        "createTime": createTime,
        "updateTime": updateTime,
        "productTime": productTime,
        "dFlag": dFlag,
        "productDescImage": productDescImage,
      };
}

class DigitalDetail extends StatefulWidget {
  @override
  _DigitalDetailState createState() => _DigitalDetailState();
}

class _DigitalDetailState extends State<DigitalDetail> {
  //点击支付选择
  List<BrnCommonActionSheetItem> actions = [];

  late List<ProductNew> productNewList;

  late ProductNew productNew;

  late Map toMap = new HashMap();

  String productCode = "";

  String orgUrl = "";

  String mylUrl = "";

  String content =
      "3D商品为虚拟3D商品,而非实物,仅限实名认证为年满18周岁的中国大陆用户购买. 3D商品的版权由发行方或原创者拥有,除另行取得版权拥有者书面同意外,用户不得将3D商品用于任何商业用途. 本商品已经售出,不支持退换.本商品源文件不支持本地下载. 请勿对3D商品进行炒作,场外交易,欺诈,或以任何其他非法方式进行使用.";

  //注册微信
  void initWxApi() {
    fluwx.registerWxApi(
      appId: "wx86906bf47492eb6f",
      universalLink: "https://help.wechat.com/app", // https://open.weixin.qq.com         https://help.wechat.com/app
    );
  }


  getBannerList()async{
    var request = await new Dio().get(API.reqUrl+"/get/banner/list");
    setState(() {
      orgUrl = request.data["dataObj"][2]["bannerUrl"].toString();
      mylUrl = request.data["dataObj"][3]["bannerUrl"].toString();
    });
    print("打印头像..........."+orgUrl);
  }



  @override
  void initState() {
    getBannerList();
    // TODO: implement initState
    super.initState();
    _getnew();
    initWxApi();
    actions.add(
      BrnCommonActionSheetItem(
        '微信支付',
        //desc: '点击后跳转微信支付',
        titleStyle: TextStyle(
          fontSize: 18,
          color: Colors.blue,
        ),
      ),
    );
    actions.add(
      BrnCommonActionSheetItem(
        '支付宝支付',
        // desc: '点击后跳转支付宝支付',
        titleStyle: TextStyle(
          fontSize: 18,
          color: Colors.blue,
        ),
      ),
    );
  }

  //String jsons = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2021003139677371&biz_content=%7B%22out_trade_no%22%3A%2223lkjsfsdg3%22%2C%22total_amount%22%3A%221%22%2C%22subject%22%3A%22%E6%95%B0%E5%AD%97%E8%97%8F%E5%93%81nft%E6%94%AF%E4%BB%98%22%2C%22product_code%22%3A%2226845645JHH%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3A%2F%2Fdemo.nftcm.cn%2Fapi%2Fget%2FCallback%2F23lkjsfsdg3%2F2&return_url=https%3A%2F%2Fdemo.nftcm.cn%2Fapi%2Fget%2FCallback%2F23lkjsfsdg3%2F2&sign=WmJyEOdUAzubRPS0FFRHcmpk%2B%2FXNjdtOjNT4kbS8%2FkBawn0klSPQk6VpytX2w8qK98%2BNKT%2BJJHEIomLxGSi%2FLmc1ndb8KDUaH8EEx7vQ%2BlIzL%2FWg2m%2FAh1tg%2FwK05NIzZoRBJf00VX9jYkM14nGkQ5%2BOOhbZv2lFxPlGWJKjOzWrLuZV2l5oSQjDsTJQCldSyb74HnL1flIw7es9%2FR5reu4F%2B5H9C5O92jWN%2Bvp%2BSilnrhEv0VedlZkkl8HKi3kUTZ9xSsYzKJT8JDEeTx52Sr6bONTj%2FB0R7KYidKiwy7Fyp7UL5hHZ9umnxf7OzfDklDz01KO6J%2F%2BkPZ1dtaj7RA%3D%3D&sign_type=RSA2&timestamp=2022-07-14+16%3A38%3A12&version=1.0";

  //创建订单
  void createOrder(String index) async {
    if (context.read<LoginProvider>().getIsLogin()) {
      if (toMap != null) {
        print("发送订单请求");
        print(context.read<LoginProvider>().getUserName().toString());
        var result = await new Dio().post(API.reqUrl + "/create/order", data: {
          "productCode": context.read<LoginProvider>().getProductDetailCode(),
          "orderCount": 1,
          "userId": int.parse(context.read<LoginProvider>().getUserName()),
        });
        if(index == "0"){
          //微信支付
          openWxPay(result.data["dataObj"].toString());
        }else if(index == "1"){
          //支付宝支付
          payOrder(result.data["dataObj"].toString());
        }

      }
    } else {
      BrnToast.show(
        "请您登录..",
        context,
        // preIcon: Image.asset(
        //   "assets/image/icon_toast_success.png",
        //   width: 24,
        //   height: 24,
        // ),
        duration: BrnDuration.short,
      );
      Navigator.of(context).pushNamed("registertwo");
    }
  }

  //订单支付
  void payOrder(String orderNo) async {
    var result = await new Dio().post(
      API.reqUrl + "/alibaba/pay/" + orderNo,
    );
    print(result);
    toAliPay(result.data["dataObj"], orderNo);
  }

  /// 支付宝支付
  void toAliPay(orderInfo, orderNo) async {
    //检测是否安装支付宝
    var result = await tobias.isAliPayInstalled();
    if (result) {
      print("安装了支付宝...");
      var payResult = await tobias.aliPay(orderInfo);
      print("打印" + payResult.toString());
      if (payResult['result'] != null) {
        if (payResult['resultStatus'] == '9000') {
          // toastShow("支付宝支付成功");
          // Get.back(result: true);
          print("支付宝支付成功");
          var results = await new Dio()
              .get(API.reqUrl + "/api/order/pay/callback/" + orderNo + "/1");
          if (results.data["flag"]) {
            print("回调成功了");
          }
          Navigator.of(context).pushNamed("orderlist");
        } else if (payResult['resultStatus'] == '6001') {
          //toastShow("支付宝支付失败");
          print("支付宝支付失败");

        } else {
          //toastShow("未知错误");
          print("未知错误");
        }
      }
    } else {
      // toastShow("未安装支付宝");
      print("未安装支付宝");
    }
  }

  //微信支付
  Future<void> openWxPay(String orderNo) async {
    var result = await new Dio().post(
      API.reqUrl + "/wxpay_app/" + orderNo,
    );
    print(result.data["package"]);

    //是否安装微信
    bool isInstalled = await fluwx.isWeChatInstalled;
    if (!isInstalled) {
      BrnToast.show("请先安装微信", context);
      return;
    }

    //调起支付
    fluwx.payWithWeChat(
      appId: result.data["data"]["appid"].toString(),
      partnerId: result.data["data"]["partnerid"].toString(),
      prepayId: result.data["data"]["prepayId"].toString(),
      packageValue: result.data["data"]["package"].toString(),
      nonceStr: result.data["data"]["nonceStr"].toString(),
      timeStamp: int.parse(result.data["data"]["timestamp"].toString()),
      sign: result.data["data"]["sign"].toString(),
    );


    //监听微信回调
    fluwx.weChatResponseEventHandler.listen((event)async {
      if(event.isSuccessful) {
        //BrnToast.show("微信支付成功", context);
        print("支付成功.....");
        print("微信支付成功");
        var results = await new Dio()
            .get(API.reqUrl + "/api/order/pay/callback/" + orderNo + "/2");
        if (results.data["flag"]) {
          print("回调成功了");
        }
        Navigator.of(context).pushNamed("orderlist");
      } else {
        BrnToast.show("微信支付失败", context);
        print("支付失败打印");
        print(event.errStr);
      }
    });
  }

  void _getnew() async {
    try {
      print("get请求");
      var result = await Dio().get(API.reqUrl +
          "/api/GxProduct/get/code/" +
          context.read<LoginProvider>().getProductDetailCode());
      print(result);

      // ProductNew? list = (result.data["dataObj"] as dynamic)
      //     .map((e) => ProductNew.fromMap((e as Map<String, dynamic>)))
      //     .toList();
      print("打印对象详情");
      setState(() {
        toMap = result.data['dataObj'];
      });
      print(result);
    } catch (e) {
      print("异常捕捉");
    }
  }

  @override
  Widget build(BuildContext context) {
    Object? teacherMap = ModalRoute.of(context)!.settings.arguments;
    print("传来的参数" + teacherMap.toString());

    setState(() {
      productCode = teacherMap.toString();
    });
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromRGBO(43, 43, 43, 1),
        elevation: 0,
        leading: InkWell(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Icon(
            Icons.arrow_back,
          ),
        ),
        //title: Text("3d效果展示"),
      ),
      //bottomNavigationBar: Padding(padding: EdgeInsets.only(bottom: 10),child: Container(width: MediaQuery.of(context).size.width,height: 60,color: Colors.green,),),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        color: Color.fromRGBO(43, 43, 43, 1),
        child: Stack(
          children: [
            ListView(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 4, right: 4),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(18),
                      color: Color.fromRGBO(60, 63, 65, 1),
                    ),
                    width: MediaQuery.of(context).size.width,
                    height: 60,
                    child: Padding(
                      padding: EdgeInsets.only(left: 15, right: 15),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                width: 40,
                                height: 40,
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        width: 1, color: Colors.white),
                                    borderRadius: BorderRadius.circular(40),
                                    image: DecorationImage(
                                        image: NetworkImage(
                                            orgUrl.toString()),
                                        fit: BoxFit.fill)),
                              ),

                              SizedBox(
                                width: 8,
                              ),
                              Container(
                                width: 130,
                                height: 40,
                                alignment: Alignment.centerLeft,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Container(
                                      alignment: Alignment.centerLeft,
                                      width: 130,
                                      height: 20,
                                      child: Text(
                                        "羚邦Medialink",
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontWeight: FontWeight.w400),
                                      ),
                                    ),
                                    Container(
                                      alignment: Alignment.centerLeft,
                                      width: 130,
                                      height: 20,
                                      child: Text(
                                        "作品3",
                                        style: TextStyle(color: Colors.white70),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          Container(
                            width: 98,
                            height: 40,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(50),
                                color: Color.fromRGBO(243, 224, 188, 1)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.add,
                                  size: 22,
                                  color: Color.fromRGBO(30, 32, 32, 1),
                                ),
                                SizedBox(
                                  width: 2,
                                ),
                                Text(
                                  "关注",
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color.fromRGBO(30, 32, 32, 1),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    height: 60,
                    child: Row(
                      mainAxisAlignment:
                      MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "作品故事",
                          style: TextStyle(
                              fontSize: 25,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                        Text(
                          "产品主页>",
                          style: TextStyle(
                              fontSize: 16,
                              color:
                              Color.fromRGBO(223, 223, 223, 1)),
                        ),
                      ],
                    ),
                  ),
                ),
                //图片
                Padding(
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Container(
                    width: double.infinity,
                    height: 1700,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      image: DecorationImage(
                          image: NetworkImage(toMap["productDescImage"].toString()),
                          fit: BoxFit.fill),
                    ),
                  ),
                ),
                // Text("sdfsdfsd"),
                // Container(width: 100,height: 100,color: Colors.green,child: Text("23424323"+toMap["productDescImage"].toString()),),
                Padding(
                    padding: EdgeInsets.only(left: 17, right: 17),
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: 30,
                      child: Row(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "创作者",
                            style: TextStyle(
                                fontSize: 14,
                                color: Colors.white70),
                          ),
                          Text(
                            "安德鲁·德·圣埃克苏佩里基金会",
                            style: TextStyle(
                                fontSize: 14, color: Colors.white),
                          ),
                        ],
                      ),
                    )),
                Padding(
                    padding: EdgeInsets.only(left: 17, right: 17),
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: 30,
                      child: Row(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "发行方",
                            style: TextStyle(
                                fontSize: 14,
                                color: Colors.white70),
                          ),
                          Text(
                            "丽邦文化创意投资有限公司",
                            style: TextStyle(
                                fontSize: 14, color: Colors.white),
                          ),
                        ],
                      ),
                    )),
                SizedBox(
                  height: 4,
                ),
                //购买须知
                Padding(
                  padding: EdgeInsets.only(left: 5, right: 5),
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    height: 235,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        color: Color.fromRGBO(60, 63, 65, 1)),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 16, top: 6),
                          child: Container(
                            alignment: Alignment.bottomLeft,
                            width: MediaQuery.of(context).size.width,
                            height: 40,
                            child: Text(
                              "购买须知",
                              textAlign: TextAlign.left,
                              style:
                                  TextStyle(fontSize: 24, color: Colors.white),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 16, top: 6, right: 16),
                          child: Container(
                            alignment: Alignment.topLeft,
                            width: MediaQuery.of(context).size.width,
                            height: 150,
                            child: Text(
                              content,
                              textAlign: TextAlign.left,
                              style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.white70,
                                  height: 1.5),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 60,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(15),
                        topRight: Radius.circular(15)),
                    color: Color.fromRGBO(12, 13, 13, 1),
                  ),
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 80,
                          height: 30,
                          child: Image.network(
                            mylUrl,
                            fit: BoxFit.fill,
                          ),
                        ),
                        Text(
                          "提供技术支持",
                          style: TextStyle(color: Colors.white70),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 20,
                  color: Color.fromRGBO(12, 13, 13, 1),
                ),
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 60,
                  color: Color.fromRGBO(12, 13, 13, 1),
                ),
              ],
            ),
            Positioned(
              bottom: 12,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: 62,
                color: Color.fromRGBO(0, 0, 0, 0.7),
                child: Padding(
                  padding: EdgeInsets.only(top: 8, bottom: 8, right: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        alignment: Alignment.center,
                        width: 100,
                        height: 55,
                        //color: Colors.orange,
                        child: Text(
                          "¥ " + toMap["initPrice"].toString() + ".00",
                          style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.w600,
                              color: Colors.white),
                        ),
                      ),
                      SizedBox(
                        width: 56,
                      ),
                      InkWell(
                        onTap: () {
                          if(context.read<LoginProvider>().isLogin){
                            print("购买提醒...");
                            //toAliPay(jsons);
                            //createOrder();
                            showModalBottomSheet(
                                context: context,
                                backgroundColor: Colors.transparent,
                                builder: (BuildContext context) {
                                  return BrnCommonActionSheet(
                                    title: "商品支付",
                                    actions: actions,
                                    maxTitleLines: 3,
                                    clickCallBack: (
                                        int index,
                                        BrnCommonActionSheetItem actionEle,
                                        ) {
                                      String title = actionEle.title;
                                      //BrnToast.show("title: $title, index: $index", context);
                                      print("选择了" + index.toString());
                                      createOrder(index.toString());
                                    },
                                    onItemClickInterceptor: (
                                        int index,
                                        BrnCommonActionSheetItem actionEle,
                                        ) {
                                      // 选项三点击事件被拦截，不作处理
                                      if (index == 2) {
                                        BrnToast.show("被拦截了", context);
                                        return true;
                                      }
                                      // 其他选项正常
                                      return false;
                                    },
                                  );
                                });
                          }else{
                            Navigator.of(context).pushNamed("registertwo");
                          }

                        },
                        child: Container(
                          width: 160,
                          height: 50,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            color: Color.fromRGBO(243, 224, 188, 1),
                          ),
                          child: Padding(
                            padding: EdgeInsets.only(top: 5, bottom: 5),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                // Text(
                                //   "设置购买提醒",
                                //   style: TextStyle(
                                //       color: Color.fromRGBO(98, 85, 62, 1),
                                //       fontSize: 15,
                                //       fontWeight: FontWeight.w600),
                                // ),
                                // Text("07.13 12:00 开售",
                                //     style: TextStyle(
                                //         color: Color.fromRGBO(146, 132, 104, 1),
                                //         fontSize: 11)),
                                Text(
                                  "立即购买",
                                  style: TextStyle(
                                      color: Color.fromRGBO(98, 85, 62, 1),
                                      fontSize: 15,
                                      fontWeight: FontWeight.w600),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
